<script>
/* eslint-disable */
import Vue from 'vue';
import { configList, bindingEquipment } from '@/api/basic';
import { verifyAccessToken } from '@/api/login';
// var jm = require('@/api/base64-min.js');
import { mapMutations } from 'vuex';
// let base64= require('./api/base64.js').Base64;
var base64 = require('@/api/base64.js').Base64;


// 测试
console.log("开始测试");
console.log(base64.encode("admin"));
console.log(base64.encode("123123"));
// 测试结束host: 'http://a1903888d0.51mypc.cn/',host: 'https://cs.zyqok.com/',host: 'https://fzjj.zyqok.com/b2/',http://3nq2729008.wicp.vip/b2/
export default {
	data() {
	    return {};
	},
	        globalData: {  
				btDevices: [
				    {
				        id: 1,
				        rssi: -40,
				        name: 'BT626',
				        devId: '0',
				        img: '/static/imgs/scan/2.png'
				    }
				],
				platform: 'ios',
				// host: 'https://fzjj.zyqok.com/b2/',
				host: uni.getStorageSync('host'),
	            zyqoid: uni.getStorageSync('zyqopenid'),
				zyqdl: uni.getStorageSync('zyqdl'),
				zyqtoken:uni.getStorageSync('zyqtoken'),
				zyqadmin:uni.getStorageSync('zyqadmin'),
				zyqpass:uni.getStorageSync('zyqpass'),
				zyqadminid:uni.getStorageSync('zyqadminid'),
				zyqname:uni.getStorageSync('zyqname')
	        },  
	onLaunch() {
		var that = this;
		uni.getSystemInfo({
		    success: function (res) {
		        console.log(res.model);
		        console.log(res.pixelRatio);
		        console.log(res.windowWidth);
		        console.log(res.windowHeight);
		        console.log(res.language);
		        console.log(res.version);
		        console.log(res.platform);
		        that.globalData.platform = res.platform;
		    }
		});
		console.log('App Launch');
		this.initData();
		// this.zyqgetoid();
		// this.zyqdl();
		//把上面2个合并 处理云函数异步问题
		this.zyqopeniddl();
	},
	onHide() {},
	methods: {
		...mapMutations(['setNotifyNum']),

		// 数据初始化
		initData() {

			// 获取页面设置配置

			const _this = this;
			const token = uni.getStorageSync('accessToken');
			// #ifdef APP-PLUS
			// 5+ push 消息推送 ps:使用:H5+的方式监听，实现推送
			plus.push.addEventListener(
				'click',
				function(msg) {
					_this.navTo(JSON.parse(msg.content));
				},
				false
			);
			// 监听在线消息事件
			plus.push.addEventListener(
				'receive',
				function(msg) {
					_this.navTo(JSON.parse(msg.content));
				},
				false
			);
			// #endif
			// 获取系统title高度
			this.initSystemInfo();
			if (token) {
				// this.handleVerifyAccessToken(token);
			}
			if (this.$mStore.getters.hasLogin) {
				// 初始化Websocket
				// await this.$mWebsocket.initWebsocket();
				// 初始化数量
				this.setNotifyNum(uni.getStorageSync('notifyNum') || 0);
				// #ifdef APP-PLUS
				const info = plus.push.getClientInfo();
				this.handleBindingEquipment(info.clientid, token);
				// #endif
			}

			
		},
		// 初始化系统信息
		initSystemInfo() {
			  //zyqfixed 开始
			    var that=this;   // 这个地方非常重要，重置data{}里数据时候setData方法的this应为以及函数的this, 如果在下方的sucess直接写this就变成了wx.request()的this了
	
			uni.getSystemInfo({
				success(e) {
					Vue.prototype.CustomId='123c';
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform === 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 43;
					}
					// #endif
					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight;
					const custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					Vue.prototype.CustomBar = custom.top - e.statusBarHeight;
					// #endif
					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
				}
			});
		},


		// 设备绑定(app推送)
		handleBindingEquipment(id, token) {
			const oauth_client = uni.getSystemInfoSync().platform;
			this.$http.post(bindingEquipment, {
				token,
				oauth_client,
				oauth_client_user_id: id
			});
		},
		handleVerifyAccessToken (token) {
			 this.$http.post(verifyAccessToken, { token }).then(r => {
				 if (!r.data.token) {
								this.$mStore.commit('logout');
				 }
			 });
         },
	// 测试
	          zyqceshi() {
		              uni.showToast({
		                        title: "我是2测试getapp.zyqceshi()",
		                        icon: 'none',
		                        mask: true,
		                        duration: 2000,
		                     })
		                },
	// 取openID
	    //异步登录
		async zyqopeniddl(){
			if(!uni.getStorageSync('zyqopenid')){
				console.log("101-没有zyqopenid");
				// let zyqok=await this.zyqrequestid();
				// let zyqok=await this.getOpenId();
				let zyqok='1234';
				// this.getOpenId();
				// console.log("102-zyqok="+zyqok);
			}	
			await this.zyqdl();
		},
		getOpenId: () => {
		    return new Promise((resolve, reject) => {
					const self = this;
					uni.login({
						success: function(res) {
							if (res.code) {
								uni.getUserInfo({
									success: function(res) {
										console.log('存在code');
									}
								});
								var appid = 'wx8932ab08989be94a'; //这里是我的appid，需要改成你自己的
								// var secret = '5b1ea6ec409968658c9f9242ec2220f8'; //密钥也要改成你自己的
								var secret = base64.decode('NWIxZWE2ZWM0MDk5Njg2NThjOWY5MjQyZWMyMjIwZjg='); //密钥也要改成你自己的
							

								// var secret = base64.encode('5b1ea6ec409968658c9f9242ec2220f8'); //密钥也要改成你自己的
								console.log('存在code'+secret);
								var openid = '';
								var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + res.code + '&grant_type=authorization_code';
								uni.request({
									url: url,
									data: {},
									method: 'GET',
									success: function(res) {
										var obj = {};
										obj.openid = res.data.openid;
										uni.setStorageSync('zyqopenid',res.data.openid);
										console.log('openid: ' + res.data.openid);
										obj.expires_in = Date.now() + res.data.expires_in;
										resolve(res.data.openid);
									}
								});
							} else {
								console.log('获取用户登录态失败！' + res.errMsg);
							}
						}
					});
			})
		},	
		//异步云函数获取openid
		zyqrequestid: () => {
		    return new Promise((resolve, reject) => {					
		        wx.cloud.init({
		          traceUser: true,
		                      })
		        wx.cloud.callFunction({
		                  name: 'quickstartFunctions',
		                  config: {
		                    env: "fzjjwx-4gpyvp3k8f6b0b55"
		                          },
		                  data: {
		                    type: 'getOpenId'
		                        }
		                     }).then((resp) => {
		        					   console.log(resp);
		        					   console.log('resp.result.openid=');
		                               console.log(resp.result.openid);
		        		 			  uni.setStorageSync('zyqopenid',resp.result.openid);
		        		 			   console.log("没有zyqopenid调用zyqdengluuni.setStorageSync");
									   resolve(resp.result.openid);
		                        })
		    })
		},	
		async zyqdl() {
			console.log("zyqdl开始------------------");
			this.globalData.host=uni.getStorageSync('host');
			if(!uni.getStorageSync('zyqopenid')){
						 uni.setStorageSync('zyqopenid','1234');
			} 
			if(!uni.getStorageSync('host')){
				console.log("zyqdl-无host跳转到登录页面");
				    wx.navigateTo({ url: `/pages/public/login`, });				
				return;
			}
			if(!uni.getStorageSync('zyquser')){
				console.log("zyqdl-无zyquser跳转到登录页面");
				    wx.navigateTo({ url: `/pages/public/login`, });				
				return;
			}
			console.log("zyqdl开始登录查询");
			let zyqurl=this.globalData.host+'api.php?';
			let zyqdata={   m:"login",
		   			        a:"check",
		   			        user:base64.encode(uni.getStorageSync('zyquser')),
		   			        pass:base64.encode(uni.getStorageSync('zyqpass')),
		   			        device:uni.getStorageSync('zyqopenid'),
		   			        cfrom:"weixin"
		   			      };
			let zyqdlxc=await this.zyqrequest(zyqurl,zyqdata);
			console.log("zyqdl查询结果");
			console.log(zyqdlxc);
			// if(zyqdlxc.code==201){
			// 	uni.showToast({title: zyqdlxc.msg,icon: 'none',mask: true,duration: 2000,});
			// }	
			if(zyqdlxc.code==200){
				console.log(zyqdlxc.data.token);
				console.log("登陆结果结束");
				uni.setStorageSync('zyqtoken',zyqdlxc.data.token);
				uni.setStorageSync('zyqadminid',zyqdlxc.data.uid);				
				uni.setStorageSync('zyqname',zyqdlxc.data.name);
				uni.setStorageSync('zyquser',zyqdlxc.data.user);
				uni.setStorageSync('zyqranking',zyqdlxc.data.ranking);
				uni.setStorageSync('zyqdeptname',zyqdlxc.data.deptname);
				uni.setStorageSync('zyqgongxv',zyqdlxc.data.gongxv);
				uni.setStorageSync('zyqhaslogin',1);
				// this.zyqduyy(zyqdlxc.data.token);
				console.log("登录/pages/profile/profile");
				uni.reLaunch({
				    url: '/pages/profile/profile'
				})
				console.log("开始读取菜单");
				
				let zyqurl=this.globalData.host+'api.php?';//请求地址
				let zyqdata={//发送给后台的数据
				  m:"agent",
				  a:"data",
				  adminid:uni.getStorageSync('zyqadminid'),
				  cfrom:"weixin",
				  token:uni.getStorageSync('zyqtoken'),
				};				
				let zyqduyy=await this.zyqrequest(zyqurl,zyqdata);
				console.log("菜单查询结果");
				console.log(zyqduyy);
				if(zyqduyy.code==200){
					let a=JSON.parse(zyqduyy.data.agentjson);
					var i,len=a.length,d,oshow,typearr={};
							for(i=0;i<len;i++){
								d 	= a[i];
								d.i = i;
								if(!typearr[d.types])typearr[d.types]=[];
								typearr[d.types].push(d);
							}
							console.log("菜单查询结果解析");
							console.log(typearr);	
					uni.setStorageSync('zyqworksList',JSON.stringify(typearr));
				}
				
			}else{
			    wx.navigateTo({ url: `/pages/public/login`, });	
				uni.showToast({title: zyqdlxc.msg,icon: 'none',mask: true,duration: 2000,});
			}
		
		},	
		async zyqzhuce2() {
				uni.showToast({title: "欧克欧克",icon: 'none',mask: true,duration: 2000,});
		},		
		async zyqzhuce() {
			console.log("zyqzhuce开始------------------");
			this.globalData.host=uni.getStorageSync('host');
			if(!uni.getStorageSync('zyqopenid')){
						 uni.setStorageSync('zyqopenid','1234');
			} 
			if(!uni.getStorageSync('host')){
				console.log("zyqdl-无host跳转到登录页面");
				    wx.navigateTo({ url: `/pages/public/login`, });				
				return;
			}
			if(!uni.getStorageSync('zyquser')){
				console.log("zyqdl-无zyquser跳转到登录页面");
				    wx.navigateTo({ url: `/pages/public/login`, });				
				return;
			}
			console.log("zyqdl开始注册查询");
			let zyqurl=this.globalData.host+'api.php?';
			let zyqdata={   m:"login",
		   			        a:"zhuce",
		   			        user:base64.encode(uni.getStorageSync('zyquser')),
		   			        pass:base64.encode(uni.getStorageSync('zyqpass')),
		   			        device:uni.getStorageSync('zyqopenid'),
		   			        cfrom:"weixin"
		   			      };
			let zyqdlxc=await this.zyqrequest(zyqurl,zyqdata);
			console.log("zyqdl查询结果");
			console.log(zyqdlxc);
			if(zyqdlxc.code==201){
				console.log(zyqdlxc.data.token);
				console.log("注册结果结束");
				uni.showToast({title: "用户名已经注册，不要重复注册！",icon: 'none',mask: true,duration: 2000,});				
			}else{
			if(zyqdlxc.code==200){
				console.log(zyqdlxc.data.token);
				console.log("注册结果结束");
				uni.showToast({title: "注册成功！请登录",icon: 'none',mask: true,duration: 2000,});				
			}else{
			    wx.navigateTo({ url: `/pages/public/login`, });	
				uni.showToast({title:  "注册失败！",icon: 'none',mask: true,duration: 2000,});
			}	
			}

		
		},	
		//异步request
		zyqrequest: (zyqurl,zyqdata) => {
		    return new Promise((resolve, reject) => {					
		        uni.request({
		            url: zyqurl,
					data:zyqdata,
		            success: (res) => {
					   resolve(res.data);
		            },
		            fail: (err) => {
						 reject(err);
		            }
		        });
		    })
		},	
		//zyqfixed 1 这个已经废弃 改成异步的那个
		zyqgetoid() {
		 if(!uni.getStorageSync('zyqopenid')){
		 	console.log("没有zyqopenid");
		       wx.cloud.init({
		         // env 参数说明：
		         //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
		         //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
		         //   如不填则使用默认环境（第一个创建的环境）
		         // env: 'my-env-id',
		         traceUser: true,
		       })
		       			// getOpenid() {
		               wx.showLoading({
		                 title: '获取openid',
		               })
		              wx.cloud.callFunction({
		                 name: 'quickstartFunctions',
		                 config: {
		                   env: "fzjjwx-4gpyvp3k8f6b0b55"
		                 },
		                 data: {
		                   type: 'getOpenId'
		                 }
		               }).then((resp) => {
		               // this.zyqoid=resp.result.openid;
					   console.log(resp);
					   console.log('resp.result.openid=');
		               console.log(resp.result.openid);
		 			  uni.setStorageSync('zyqopenid',resp.result.openid);
		               // this.$mHelper.toast('取得id:'+resp.result.openid);
		                wx.hideLoading();
		 			   console.log("没有zyqopenid调用zyqdenglu");
		 			   return resp.result.openid;
		              }).catch((e) => {
		                wx.hideLoading()
		               })
		 			  }else{
		 				  console.log("有zyqopenid调用zyqdenglu");
		 				 return uni.getStorageSync('zyqopenid');  
		 			  }
		},	
		//登录无参数这个已经废弃 改成异步的那个
	    zyqdl2() {
		 console.log("1-1登陆开始oid:"+uni.getStorageSync('zyqopenid'));
		 if(!uni.getStorageSync('zyqopenid')){
			 uni.setStorageSync('zyqopenid','1234');
			} 
		 	console.log("1-2登陆开始oid:"+uni.getStorageSync('zyqopenid'));
		 	if(!uni.getStorageSync('zyquser')){
		 		console.log("2登陆开始oid:"+uni.getStorageSync('zyqopenid'));
		 		    wx.navigateTo({ url: `/pages/public/login`, });
		 		
		 		return;
		 	}
		   //zyqfixed 登陆开始
		   
		   var that=this;
		   				console.log("3登陆开始oid:"+uni.getStorageSync('zyqopenid'));
		   				wx.request({
		   			      url:that.globalData.host+'api.php?',//请求地址
		   			      data:{//发送给后台的数据
		   			        m:"login",
		   			        a:"check",
		   			        user:base64.encode(uni.getStorageSync('zyquser')),
		   			        pass:base64.encode(uni.getStorageSync('zyqpass')),
		   			        device:uni.getStorageSync('zyqopenid'),
		   			        cfrom:"weixin"
		   			      },
		   			      header:{//请求头
		   			        // "Content-Type":"applciation/json",
		   					"Content-Type":"text/html; charset=UTF-8",
		   			      },
		   			      method:"GET",//get为默认方法/POST
		   			      success:function(res){
		   					console.log("登陆结果");
		   			        console.log(res.data);//res.data相当于ajax里面的data,为后台返回的数据
		 					if(res.data.code==200){
		 						console.log(res.data.data.token);
		 						console.log("登陆结果结束");
		 						uni.setStorageSync('zyqtoken',res.data.data.token);
		 						uni.setStorageSync('zyqadminid',res.data.data.uid);
								
								uni.setStorageSync('zyqname',res.data.data.name);
								console.log(res.data.data.name);
								uni.setStorageSync('zyquser',res.data.data.user);
								uni.setStorageSync('zyqranking',res.data.data.ranking);
								uni.setStorageSync('zyqdeptname',res.data.data.deptname);
								uni.setStorageSync('zyqhaslogin',1);
		 						that.zyqduyy(res.data.data.token);
								// wx.navigateTo({ url: `/pages/index/index`, });
								console.log("/pages/application/index");
								uni.reLaunch({
								    url: '/pages/profile/profile'
								})
								// uni.switchTab({
								//          url: '/pages/profile/profile',
								// 		 // success: function () {
								// 		 //     var page = getCurrentPages().pop();
								// 		 //     if (page == undefined || page == null) return;
								// 		 //     page.onLoad(); //重新刷新device-info页面
								// 		 //   }
								// });
								console.log("完成pages/application/index");
		 						
		 					}else{
		 						wx.navigateTo({ url: `/pages/public/login`, });
		 					}

		   			 
		   			      },
		   			      fail:function(err){
		 					  wx.navigateTo({ url: `/pages/public/login`, });
		 
		 				  },//请求失败
		   			      complete:function(){}//请求完成后执行的函数
		   			    })
		   //zyqfixed 登陆结束
		 
	 },
		//读菜单这个已经废弃 改成异步的那个
		zyqduyy2() {
			//zyqfixed 读应用开始
			var that=this;
			               console.log("读应用开始");
							wx.request({
						      url:that.globalData.host+'api.php?',//请求地址
						      data:{//发送给后台的数据
						        m:"agent",
						        a:"data",
						        adminid:uni.getStorageSync('zyqadminid'),
						        cfrom:"weixin",
						        token:uni.getStorageSync('zyqtoken'),
						      },
						      header:{//请求头
						        // "Content-Type":"applciation/json",
								"Content-Type":"text/html; charset=UTF-8",
						      },
						      method:"GET",//get为默认方法/POST
						      success:function(res){
						        console.log(res.data);//res.data相当于ajax里面的data,为后台返回的数据
									// uni.setStorageSync('zyqworksList',res.data.data.agentjson);
									let a=JSON.parse(res.data.data.agentjson);
									var i,len=a.length,d,oshow,typearr={};
											for(i=0;i<len;i++){
												d 	= a[i];
												d.i = i;
												if(!typearr[d.types])typearr[d.types]=[];
												typearr[d.types].push(d);
											}
											console.log("typearr");
											console.log(typearr);								
											// uni.setStorageSync('zyqworksList',JSON.stringify(typearr));
									
									if(res.data.code==200){
										uni.setStorageSync('zyqworksList',JSON.stringify(typearr));
									}
									else{
										wx.navigateTo({ url: `/pages/public/login`, });
									}
						 
						      },
						      fail:function(err){},//请求失败
						      complete:function(){}//请求完成后执行的函数
						    })
			//zyqfixed 读应用结束
			},
		// 推送消息跳转
		navTo(item) {
			let route;
			const id = item.target_id;
			const type = item.target_type;
			switch (type) {
				
				default:
					route = '/pages/index/index';
					break;
			}
			if (route) this.$mRouter.push({ route });
		},
	}
};
</script>
<style lang="scss">
// 导入colorUI
@import '/static/css/colorui/main.css';
@import '/static/css/colorui/icon.css';
@import '/static/css/colorui/animation.css';
// 导入阿里巴巴矢量图标库
/*#ifdef MP*/
@import './static/css/iconfont/iconfont.css';
/*#endif*/
/*#ifndef MP*/
@import url('https://at.alicdn.com/t/font_1823374_98c45zxwb3c.css');
/*#endif*/
@import './static/css/reset.scss';
@import './static/css/uni.scss';
</style>
